package org.ponly.cta4j.drawing.filter;

import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 基于 jdk {@link BufferedImageOp} 实现的滤镜.
 *
 * @author vacoor
 * @since 1.0
 */
public class BufferedImageOpFilter implements Filter {
    private List<BufferedImageOp> imageOperations = new ArrayList<BufferedImageOp>();

    /**
     * 创建默认滤镜实例.
     */
    public BufferedImageOpFilter() {
    }

    /**
     * 使用给定的 BufferedImageOp 创建一个滤镜.
     *
     * @param imageOperations BufferedImageOp
     */
    public BufferedImageOpFilter(final BufferedImageOp... imageOperations) {
        addOperations(imageOperations);
    }

    /**
     * 使用给定的 BufferedImageOp 创建一个滤镜.
     *
     * @param imageOperations BufferedImageOp
     */
    public BufferedImageOpFilter(final List<BufferedImageOp> imageOperations) {
        this.imageOperations.addAll(imageOperations);
    }

    /**
     * 将给定 BufferedImageOp 加入当前滤镜中.
     *
     * @param imageOperations BufferedImageOp
     * @return 当前滤镜
     */
    public BufferedImageOpFilter addOperations(final BufferedImageOp... imageOperations) {
        Collections.addAll(this.imageOperations, imageOperations);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public BufferedImage apply(final BufferedImage image) {
        BufferedImage target = image;
        for (final BufferedImageOp operation : imageOperations) {
            target = operation.filter(target, null);
        }
        return target;
    }

    /**
     * 使用给定的 BufferedImageOp 创建一个 BufferedImageOpFilter.
     *
     * @param imageOperations BufferedImageOp 数组
     * @return BufferedImageOpFilter
     */
    public static BufferedImageOpFilter create(final BufferedImageOp... imageOperations) {
        return new BufferedImageOpFilter(imageOperations);
    }
}
